package com.sg.common.empty.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.sg.common.empty.service.CfgService;
import com.sg.common.utils.Constant;

public class Params2 {
	HttpServletRequest request;
	CfgService service;
	Map<String, Object> rb;

	public static Params2 init(HttpServletRequest request,Map<String, Object> rb, CfgService service) {
		Params2 res = new Params2();
		res.request = request;
		res.service = service;
		res.rb = rb;
		return res;
	}

	@SuppressWarnings("unchecked")
	public List<String> build() {
		String route = (String) request.getAttribute("conf.route");
		List<String> ps = Constant.getStringList(route + ".params");
		List<String> sqlParams = new ArrayList<String>();

		for (String param : ps) {
			String beanValue = "";
			if (StringUtils.contains(param, "`")) {
				String[] split = StringUtils.split(param, "`");
				if (StringUtils.equals(split[0], "request")) {
					beanValue =  Constant.getRbString(rb,split[1]);
				} else if (StringUtils.equals(split[0], "requestArray")) {
					List<String> temp = Constant.getRbList(rb,split[1]);
					if(temp.size()>0)
						beanValue =JSONArray.toJSONString(temp);
					else {
							beanValue ="";
					}
				}
			} else {
				beanValue = (String) FilterVal.init(param, service).get2();
			}
			sqlParams.add(beanValue);
		}
		return sqlParams;
	}
	
	@SuppressWarnings("unchecked")
	public List<String> build(List<String> ps) {
//		String route = (String) request.getAttribute("conf.route");
//		List<String> ps = Constant.getStringList(route + ".params");
		List<String> sqlParams = new ArrayList<String>();

		for (String param : ps) {
			String beanValue = "";
			if (StringUtils.contains(param, "`")) {
				String[] split = StringUtils.split(param, "`");
				if (StringUtils.equals(split[0], "request")) {
					beanValue =  Constant.getRbString(rb,split[1]);
				} else if (StringUtils.equals(split[0], "requestArray")) {
					List<String> temp = Constant.getRbList(rb,split[1]);
					if(temp.size()>0)
						beanValue =JSONArray.toJSONString(temp);
					else {
							beanValue ="";
					}
				}
			} else {
				beanValue = (String) FilterVal.init(param, service).get2();
			}
			sqlParams.add(beanValue);
		}
		return sqlParams;
	}
}
